package SQL.scan;

import heap.ResultRow;
import heap.ResultSchema;

public class ProductScan implements Scan {

	public ProductScan(Scan s1, Scan s2) throws Exception{
		this.s1 = s1;
		this.s2 = s2;
		ResultSchema schema1 = s1.getSchema();
		ResultSchema schema2 = s2.getSchema();
		schema = new ResultSchema();
		for(int i = 0;i<schema1.size();i++){
			schema.add(schema1.get(i));
		}
		for(int i = 0;i<schema2.size();i++){
			schema.add(schema2.get(i));
		}
		s1.next();
	}
	
	public void beforeFirst() throws Exception {
		s1.beforeFirst();
		s1.next();
		s2.beforeFirst();
	}

	@Override
	public void close() throws Exception {
		s1.close();
		s2.close();
	}

	@Override
	public ResultRow getCurrent() throws Exception {
		return result;
	}

	@Override
	public ResultSchema getSchema() throws Exception {
		return schema;
	}

	@Override
	public boolean hasField(String fldname) throws Exception {
		return s1.hasField(fldname)||s2.hasField(fldname);
	}

	@Override
	public ResultRow next() throws Exception {
		if(s1.getCurrent() == null)
			return null;
		if(s2.next() == null){
			s2.beforeFirst();
			if((s1.next() == null) || (s2.next()==null)){
				return null;
			}
		}
		ResultRow row1 = s1.getCurrent();
		ResultRow row2 = s2.getCurrent();
		result = new ResultRow();
		for(int i=0;i<row1.size();i++){
			result.add(row1.get(i));
		}
		for(int i=0;i<row2.size();i++){
			result.add(row2.get(i));
		}
		return result;
	}
	

	private Scan s1,s2;
	private ResultRow result;
	private ResultSchema schema;
	

}
